//---------------------------------------------------------------------------
/**
 * \class CLog
 * \brief This is a class for logging
 * \version 0.1
 *
 * \author Woo-Hyun Kim (woorung@nhncorp.com, woorung@gmail.com)
 * \author http://blog.naver.com/wisereign .
 *
 * \date 2008/09/22
 */
//---------------------------------------------------------------------------
#include "CLog.h"
#include "lock/CLock.h"

CLog::CLog()
{
	logfullfile = DEFAULT_LOG_FILE;

	string::size_type pos = logfullfile.rfind(".");
	if(pos==string::npos) {
		logpath = logfullfile;
		logext = "";
	}
	else {
		logpath = logfullfile.substr(0, pos);
		logext = logfullfile.substr(pos+1);
	}
}

CLog::CLog(char *file)
{
	logfullfile = file;

	string::size_type pos = logfullfile.rfind(".");
	if(pos==string::npos) {
		logpath = logfullfile;
		logext = "";
	}
	else {
		logpath = logfullfile.substr(0, pos);
		logext = logfullfile.substr(pos+1);
	}
}

CLog::~CLog()
{
}

int CLog::print(char *msg)
{
	return print(msg, -1, NULL);
}

int CLog::print(char *msg, long line_num, char *source_file)
{
	struct timeb itb;
	struct tm *lt;
	ftime(&itb);
	lt = localtime(&itb.time);

	char cur_date[1024];
	sprintf(cur_date, "%04d%02d%02d", lt->tm_year+1900, lt->tm_mon+1, lt->tm_mday);

	char cur_time[1024];
	sprintf(cur_time, "%02d:%02d:%02d", lt->tm_hour, lt->tm_min, lt->tm_sec);

	char dailylogfullfile[1024];
	if(logext!="") sprintf(dailylogfullfile, "%s.%s.%s", (char *)logpath.c_str(), cur_date, (char *)logext.c_str());
	else sprintf(dailylogfullfile, "%s.%s", (char *)logpath.c_str(), cur_date);

	ofstream fout(dailylogfullfile, ios::app|ios::out);

	char lock_file[1024];
	sprintf(lock_file, "%s.lck", (char *)logpath.c_str());

	// lock-on
	// --------------------------------------------------------------------------
	CLock lock(lock_file);
	if(lock.lock()!=0) {
		cerr << "### error : file lock failure in CLog::print()" << endl;
		
		fout.close();
		return -1;
	}
	// --------------------------------------------------------------------------
	
	if(line_num>=0&&source_file!=NULL) fout << "[" << cur_date << " " << cur_time<< "]" << msg << "\t(" << line_num << " line in "<<  source_file << ")" << endl;
	else fout << "[" << cur_date << " " << cur_time<< "]" << msg << endl;

	// lock-off
	// --------------------------------------------------------------------------
	if(lock.unlock()!=0) {
		cerr << "### error : file unlock failure in CLog::print()" << endl;
		
		fout.close();
		return -1;
	}
	// --------------------------------------------------------------------------

	fout.close();

	return 1;
}
